package com.chinda.common.security.handler;

import com.chinda.common.enums.MessageEnum;
import com.chinda.common.security.SysUserDetails;
import com.chinda.common.utils.R;
import com.chinda.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登出成功处理类
 *
 * @author Wang Chinda
 * @date 2020/7/11
 * @see
 * @since 1.0
 */
@Slf4j
@Component
public class UserLogoutSuccessHandler implements LogoutSuccessHandler {

    /**
     * 登出成功返回
     * 登出应该清除Token, 前端也应该清除token
     * @param request
     * @param response
     * @param authentication
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        request.getRequestDispatcher("/filter/logout").forward(request, response);
        SysUserDetails userDetails =  (SysUserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        SecurityContextHolder.clearContext();
        log.info(MessageEnum.SYS_SECURITY_0003.getMsg(username));
        ResponseUtil.outJson(response, R.ok(MessageEnum.SYS_SECURITY_0003.getMsg(username)));
    }
}
